<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
        :closable="false"
      ></el-alert>

      <!-- 级联选择器区域 -->
      选择商品分类：
      <el-cascader
        v-model="paramsCascaderKeys"
        :options="getgoodsClassifyListData"
        :props="paramsCascaderProps"
        @change="paramsCascaderHandleChange"
      ></el-cascader>

      <!-- 标签页区域 -->
      <el-tabs
        v-model="paramsTabsActiveName"
        @tab-click="paramsTabsHandleClick"
      >
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            :disabled="isButtonDisabled"
            size="mini"
            @click="addParansBtn"
          >
            添加参数
          </el-button>
          <!-- 动态参数表格区域 -->
          <el-table :data="manyParamsData" style="width: 100%" border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  @close="paramsTagClose(index, scope.row)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.paramsInputVisible"
                  v-model="scope.row.paramsInputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="paramsHandleInputConfirm(scope.row)"
                  @blur="paramsHandleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="paramsShowInput(scope.row)"
                >
                  + New Tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- 编辑 -->
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editParamsBtn(scope.row)"
                >
                  编辑
                </el-button>
                <!-- 删除 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParamsBtn(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态参数" name="only">
          <el-button
            type="primary"
            :disabled="isButtonDisabled"
            size="mini"
            @click="addParansBtn"
          >
            添加属性
          </el-button>
          <!-- 静态参数 -->
          <el-table :data="onlyParamsData" style="width: 100%" border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  @close="paramsTagClose(index, scope.row)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.paramsInputVisible"
                  v-model="scope.row.paramsInputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="paramsHandleInputConfirm(scope.row)"
                  @blur="paramsHandleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="paramsShowInput(scope.row)"
                >
                  + New Tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="属性名称"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- 编辑 -->
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editParamsBtn(scope.row)"
                >
                  编辑
                </el-button>
                <!-- 删除 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParamsBtn(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加动态参数/静态属性对话框 -->
    <el-dialog
      :title="'添加' + addDialogVisibleTitle"
      :visible.sync="addParamsDialogVisible"
      width="50%"
      @close="addParamsDialogVisibleClose"
    >
      <el-form
        :model="paramsAddParamsDialogVisibleForm"
        :rules="paramsAddParamsDialogVisibleFormRules"
        label-width="80px"
        ref="paramsAddParamsDialogVisibleFormRef"
      >
        <el-form-item :label="addDialogVisibleTitle" prop="attr_name">
          <el-input
            v-model="paramsAddParamsDialogVisibleForm.attr_name"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">
          确 定
        </el-button>
      </span>
    </el-dialog>

    <!-- 修改动态参数/静态属性对话框 -->
    <el-dialog
      :title="'修改' + addDialogVisibleTitle"
      :visible.sync="editParamsDialogVisible"
      width="50%"
    >
      <el-form
        :model="paramsEditParamsDialogVisibleForm"
        :rules="paramsAddParamsDialogVisibleFormRules"
        label-width="80px"
        ref="paramsEditParamsDialogVisibleFormRef"
      >
        <el-form-item :label="addDialogVisibleTitle" prop="attr_name">
          <el-input
            v-model="paramsEditParamsDialogVisibleForm.attr_name"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">
          确 定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 获取商品分类数据
      getgoodsClassifyListData: [],
      // 级联选择器配置选项
      paramsCascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 级联选择器双向数据绑定
      paramsCascaderKeys: [],
      // 默认选择Tbas选中选项卡的 name
      paramsTabsActiveName: 'many',
      // 静态参数
      onlyParamsData: [],
      // 动态参数
      manyParamsData: [],
      // 控制添加动态参数/静态属性对话框显示与隐藏
      addParamsDialogVisible: false,
      // 添加参数表单数据对象
      paramsAddParamsDialogVisibleForm: {
        attr_name: ''
      },
      // 表单验证规则
      paramsAddParamsDialogVisibleFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      // 控制修改动态参数/静态属性对话框显示与隐藏
      editParamsDialogVisible: false,
      // 编辑参数表单数据对象
      paramsEditParamsDialogVisibleForm: {
        attrId: '',
        attr_name: ''
      }
    }
  },
  created() {
    this.getgoodsClassifyList()
  },
  methods: {
    // 获取商品分类数据
    async getgoodsClassifyList() {
      const { data: res } = await this.$http.get('categories', {
        params: {
          type: 3
        }
      })
      this.getgoodsClassifyListData = res.data
    },
    // 当级联选择器发生改变的时候触发
    paramsCascaderHandleChange() {
      if (this.paramsCascaderKeys.length !== 3) {
        this.paramsCascaderKeys = []
        // 静态参数
        this.onlyParamsData = []
        // 动态参数
        this.manyParamsData = []
        return
      }
      // 发送请求获取动态参数，静态参数
      this.getParams()
    },
    // tab 被选中时触发
    paramsTabsHandleClick() {
      // 发送请求获取动态参数，静态参数
      this.getParams()
    },
    // 发送请求获取动态参数，静态参数
    async getParams() {
      const { data: res } = await this.$http.get(
        `categories/${this.getClassifyId}/attributes`,
        {
          params: {
            sel: this.paramsTabsActiveName
          }
        }
      )
      // console.log(res)
      if (res.meta.status !== 200) return this.$message(res.meta.msg)
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 自定义属性
        item.paramsInputVisible = false
        item.paramsInputValue = ''
      })
      console.log(res)
      if (this.paramsTabsActiveName === 'many') {
        this.manyParamsData = res.data
      } else {
        this.onlyParamsData = res.data
      }
      this.$message.success(res.meta.msg)
    },
    // 添加动态参数/静态属性按钮
    addParansBtn() {
      // 显示添加动态参数/静态属性对话框
      this.addParamsDialogVisible = true
    },
    // 关闭添加动态参数/静态属性对话框回调函数
    addParamsDialogVisibleClose() {
      // 重置表单
      this.$refs.paramsAddParamsDialogVisibleFormRef.resetFields()
    },
    // 向后台发送请求添加动态参数/静态属性
    addParams() {
      this.$refs.paramsAddParamsDialogVisibleFormRef.validate(async vdate => {
        // console.log(vdate)
        if (!vdate) return false
        const { data: res } = await this.$http.post(
          `categories/${this.getClassifyId}/attributes`,
          {
            attr_name: this.paramsAddParamsDialogVisibleForm.attr_name,
            attr_sel: this.paramsTabsActiveName
          }
        )
        console.log(res)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        // 关闭添加动态参数/静态属性对话框
        this.addParamsDialogVisible = false
      })
    },
    // 编辑动态参数/静态属性按钮
    editParamsBtn(scope) {
      console.log(scope)
      // 当前属性的ID
      this.paramsEditParamsDialogVisibleForm.attrId = scope.attr_id
      this.paramsEditParamsDialogVisibleForm.attr_name = scope.attr_name
      // 显示修改动态参数/静态属性对话框显示与隐藏
      this.editParamsDialogVisible = true
    },
    // 向后台发送请求修改动态参数/静态属性
    editParams() {
      this.$refs.paramsEditParamsDialogVisibleFormRef.validate(async vdate => {
        if (!vdate) return false
        // 发送请求
        const { data: res } = await this.$http.put(
          `categories/${this.getClassifyId}/attributes/${this.paramsEditParamsDialogVisibleForm.attrId}`,
          {
            attr_name: this.paramsEditParamsDialogVisibleForm.attr_name,
            attr_sel: this.paramsTabsActiveName
          }
        )
        console.log(res)
        // 关闭添加动态参数/静态属性对话框
        this.editParamsDialogVisible = false
        // 重新发送请求刷新页面
        this.getParams()
      })
    },
    // 删除动态参数/静态属性按钮
    async removeParamsBtn(id) {
      const resConfirm = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(error => error)
      if (resConfirm !== 'confirm') return this.$message.info('已取消删除!')
      // 发送请求
      const { data: res } = await this.$http.delete(
        `categories/${this.getClassifyId}/attributes/${id.attr_id}`
      )
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 提示
      this.$message.success(res.meta.msg)
      // 重新发送请求刷新页面
      this.getParams()
    },
    // 点击动态编辑标签
    paramsShowInput(scope) {
      scope.paramsInputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 按下回车或输入框失去焦点都会触发
    paramsHandleInputConfirm(scope) {
      console.log(scope)
      if (scope.paramsInputValue.trim().length === 0) {
        scope.paramsInputValue = ''
        scope.paramsInputVisible = false
        return
      }
      scope.paramsInputVisible = false
      scope.attr_vals.push(scope.paramsInputValue)
      scope.paramsInputValue = ''
      // 编辑提交参数发送请求
      this.getEditParams(scope)
    },
    // 删除Tag标签触发
    paramsTagClose(i, scope) {
      // 删除
      scope.attr_vals.splice(i, 1)
      // 编辑提交参数发送请求
      this.getEditParams(scope)
    },
    // 编辑提交参数发送请求
    async getEditParams(scope) {
      const { data: res } = await this.$http.put(
        `categories/${this.getClassifyId}/attributes/${scope.attr_id}`,
        {
          attr_name: scope.attr_name,
          attr_sel: scope.attr_sel,
          attr_vals: scope.attr_vals.join(' ')
        }
      )
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
    }
  },
  computed: {
    isButtonDisabled() {
      return this.paramsCascaderKeys.length !== 3
    },
    getClassifyId() {
      if (this.paramsCascaderKeys.length === 3) {
        // console.log(this.paramsCascaderKeys)
        return this.paramsCascaderKeys[this.paramsCascaderKeys.length - 1]
      }
      return null
    },
    // 动态显示添加动态参数/静态属性标题
    addDialogVisibleTitle() {
      if (this.paramsTabsActiveName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.el-alert {
  margin-bottom: 15px;
  font-size: 18px;
}

.el-tabs {
  margin-top: 15px;
}

.el-tag {
  margin-right: 20px;
}

.input-new-tag {
  width: 120px;
}
</style>
